/**
 * 
 */
package edu.hunau.sax;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * SAX对XML的支持
 */
public class SAX4Xml {

	@Test
	public void testParse()throws Exception {
		parseXML();
	}

	/**
	 * 使用SAX解析指定的XML文档
	 * 
	 * @throws Exception
	 */
	public static void parseXML() throws Exception, Exception {
		// 1.获得工厂对象
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 2.获得解析器
		SAXParser parser = factory.newSAXParser();
		// 3.解析指定的XML文档
		parser.parse("./src/main/resources/students.xml", new MyHandler());
	}

	private static class MyHandler extends DefaultHandler {
		/* 文档开始时执行 */
		public void startDocument() throws SAXException {
			System.out.println("===文档开始===");
		}

		/* 文档结束执行 */
		public void endDocument() throws SAXException {
			System.out.println("===文档结束===");
		}

		/* 开始元素 */
		public void startElement(String uri, String localName, String qName,
				Attributes atts) throws SAXException {
			System.out.println("\t----元素开始----");
			System.out.println("\t uri=" + uri);
			System.out.println("\t localName=" + localName);
			System.out.println("\t qName=" + qName);
			System.out.println("\t 属性");
			System.out.println("\t 属性的个数=" + atts.getLength());
			for (int i = 0; i < atts.getLength(); i++) {
				System.out.println("\t" + atts.getLocalName(i) + "="
						+ atts.getValue(i));
			}
		}
		/* 标签体 */
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			System.out.println("\t\t ***标签体***");
			System.out.println("\t\t 内容:" + new String(ch, start, length));
		}
		/* 结束元素 */
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			System.out.println("\t----元素结束----");
		}

	}

}
